package com.walk.zworld.ui.location;

import android.content.Intent;
import android.graphics.Bitmap;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.AbsoluteSizeSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.base.lib.base.utils.ToastUtil;
import com.base.lib.base.view.BaseFragment;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.king.zxing.util.CodeUtils;
import com.walk.zworld.R;
import com.walk.zworld.api.HtmlConfig;
import com.walk.zworld.api.MainAPI;
import com.walk.zworld.api.bean.ChatGiftBean;
import com.walk.zworld.api.bean.MainUserSectionBean;
import com.walk.zworld.api.bean.MenuBean;
import com.walk.zworld.api.bean.OrderStatementBean;
import com.walk.zworld.api.bean.UserBean;
import com.walk.zworld.api.http.CommonAppConfig;
import com.walk.zworld.api.http.HttpCallback;
import com.walk.zworld.api.http.JumpInterceptor;
import com.walk.zworld.api.utils.DebugUtil;
import com.walk.zworld.api.utils.ListUtil;
import com.walk.zworld.api.utils.RequestFactory;
import com.walk.zworld.ui.MainActivity;
import com.walk.zworld.ui.activity.JoinTuiGuangActivity;
import com.walk.zworld.ui.activity.MyDetailActivity;
import com.walk.zworld.utils.FileUtils;
import com.walk.zworld.utils.ImgLoader;
import com.walk.zworld.utils.observer.DefaultObserver;
import com.walk.zworld.view.my.DrawableTextView;
import com.walk.zworld.webView.WebViewActivity;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import io.reactivex.ObservableSource;
import io.reactivex.functions.Function;

public class MyDetailFragment extends BaseFragment implements View.OnClickListener,OnItemClickListener {

    public static MyDetailFragment newsInstance() {
        return new MyDetailFragment();
    }

    private static final int OPENSTORE=183; //开通店铺
    private static final int MY_MONEY=138; //我的钱包
    private static final int MY_ADDR=139; //我的地址
    private static final int MY_COLLECT=140; //我的收藏
    private static final int CONNECT_SERVICE=141; //联系客服

    private static final int MY_CONSIGNMENT=142; //我的代销
    private static final int CONSIGNMENT_GOOD_MANNGER=143; //商品管理
    private static final int CONSIGNMENT_ORDER=144; //代销订单
    private static final int CONSIGNMENT_MONEY=145; //代销收益

    private static final int MY_STORE=146; //我的店铺
    private static final int STORE_ORDER=147; //店铺订单
    private static final int STORE_MONEY=148; //店铺收益
    private static final int OPEN=150; //店铺收益

    private static final int SETTING=149; //店铺收益
    private static final int MY_DIAMONDS=182; //我的钻石
    private static final int GIFT_PROFIT=186; //礼物收益

    private TextView mTvUserId;
    private ImageView mImgAvator;
    private TextView mImgVip;
    private TextView mTvUserName;
    private TextView mTvOrderTip;
    private TextView mBtnWaitPay;
    private TextView mBtnWaitDelivered;
    private TextView mBtnWaitReceived;
    private TextView mBtnWaitEvaluated;
    private TextView mBtnRefund;

    private TextView mPointWaitPay;
    private TextView mPointWaitDelivered;
    private TextView mPointWaitReceived;
    private TextView mPointWaitEvaluated;
    private TextView mPointWaitRefund;
    private TextView mBtnCheckDeail;
    private TextView mTvCurrentMoney;
    private TextView mTvYesterdayMoney;
    private TextView mTvSpreadPersonNum;
    private TextView mTvSpreadNum;

    private RecyclerView mReclyView;

    private MainUserAdapter mMenuUserAdapter;

    @Override
    public int onBindLayout() {
        return R.layout.main_home_user_fragment;
    }

    @Override
    public void initView(@NonNull View mView) {
        mImgAvator = findViewById(R.id.img_avator);
        mImgVip = findViewById(R.id.img_vip);
        FileUtils.Companion.load("",mImgAvator,true);

        mTvUserId = (TextView) findViewById(R.id.tv_user_id);
        mTvUserName = (TextView) findViewById(R.id.tv_user_name);
        mTvOrderTip = (TextView) findViewById(R.id.tv_order_tip);
        mBtnWaitPay =  findViewById(R.id.btn_wait_pay);
        mBtnWaitDelivered = findViewById(R.id.btn_wait_delivered);
        mBtnWaitReceived = findViewById(R.id.btn_wait_received);
        mBtnWaitEvaluated =  findViewById(R.id.btn_wait_evaluated);
        mBtnRefund = findViewById(R.id.btn_refund);

        mBtnWaitPay.setOnClickListener(this);
        mBtnWaitDelivered.setOnClickListener(this);
        mBtnWaitReceived.setOnClickListener(this);
        mBtnWaitEvaluated.setOnClickListener(this);
        mBtnRefund.setOnClickListener(this);

        mImgAvator.setOnClickListener(this);
        mTvUserName.setOnClickListener(this);
        mTvUserId.setOnClickListener(this);

        findViewById(R.id.btn_my_order).setOnClickListener(this);

        mPointWaitPay = (TextView) findViewById(R.id.point_wait_pay);
        mPointWaitDelivered = (TextView) findViewById(R.id.point_wait_delivered);
        mPointWaitReceived = (TextView) findViewById(R.id.point_wait_received);
        mPointWaitEvaluated = (TextView) findViewById(R.id.point_wait_evaluated);
        mPointWaitRefund = (TextView) findViewById(R.id.point_wait_refund);

        mBtnCheckDeail = (DrawableTextView) findViewById(R.id.btn_check_deail);
        mTvCurrentMoney = (TextView) findViewById(R.id.tv_current_money);
        mTvYesterdayMoney = (TextView) findViewById(R.id.tv_yesterday_money);
        mTvSpreadPersonNum = (TextView) findViewById(R.id.tv_spread_person_num);
        mTvSpreadNum = (TextView) findViewById(R.id.tv_spread_num);
        initReclyView();
        mTvCurrentMoney.setOnClickListener(this);
        mTvYesterdayMoney.setOnClickListener(this);
        mTvSpreadPersonNum.setOnClickListener(this);
        mBtnCheckDeail.setOnClickListener(this);
        mTvSpreadNum.setOnClickListener(this);
        findViewById(R.id.tv_current_money_tip).setOnClickListener(this);
        findViewById(R.id.tv_yesterday_money_tip).setOnClickListener(this);
        findViewById(R.id.tv_spread_person_num_tip).setOnClickListener(this);
        findViewById(R.id.tv_spread_num_tip).setOnClickListener(this);
//        LiveEventBus.get(MainEvent.UPDATE_USER_CENTER).observe(getActivity(), new Observer<Object>() {
//            @Override
//            public void onChanged(Object object){
//                requestData();
//            }
//        });
    }
    @Override
    public void initData() {
    }

    private void initReclyView() {
        mReclyView =  findViewById(R.id.reclyView);
        mMenuUserAdapter=new MainUserAdapter(null);
        mReclyView.setAdapter(mMenuUserAdapter);
        mMenuUserAdapter.setMenuClickListner(this);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
        mReclyView.setLayoutManager(linearLayoutManager);
        mMenuUserAdapter.setMenuClickListner(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        requestData();
    }

    private void requestData() {
        mImgAvator.setVisibility(View.INVISIBLE);
        mImgVip.setVisibility(View.GONE);
        mTvUserName.setVisibility(View.INVISIBLE);
        mTvUserId.setVisibility(View.INVISIBLE);
        RequestFactory.getRequestManager().cancle(MainAPI.USER);
        RequestFactory.getRequestManager().cancle(MainAPI.MENU_USER);
        MainAPI.getUserCenter().map(info -> {
            parseUserCenterOntherData(info);
            boolean isShop= info.getIntValue("isshop")==1;
            boolean isVip= info.getIntValue("isVip")==1;
            List<MainUserSectionBean>list=new ArrayList<>();
            if (!isVip) {
                MainUserSectionBean mainUserSectionBean2=new MainUserSectionBean();
                mainUserSectionBean2.setTitle("兑换VIP");
                mainUserSectionBean2.setId(MY_STORE);
                List<MenuBean>list2= ListUtil.asList(
                        new MenuBean("日卡(1)",9001,R.drawable.icon_main_my_vip),
                        new MenuBean("月卡(20)",9002,R.drawable.icon_main_my_vip),
                        new MenuBean("年卡(199)",9003,R.drawable.icon_main_my_vip)
//                    new MenuBean("我要开播",OPEN,R.drawable.icon_open_live)
                );
                mainUserSectionBean2.setMenuBeanList(list2);
                list.add(mainUserSectionBean2);
            }else {
                long endVipTime = info.getLongValue("endVipTime");
                mImgVip.setVisibility(View.VISIBLE);
                if (endVipTime != 0) {
                    long hour = endVipTime / 60 / 60;
                    mImgVip.setText(hour+"小时");
                }
            }
            MainUserSectionBean mainUserSectionBean2=new MainUserSectionBean();
            mainUserSectionBean2.setTitle("钻石");
            mainUserSectionBean2.setId(MY_STORE);
            List<MenuBean>list2= ListUtil.asList(
                    new MenuBean("去充值",10002,R.drawable.icon_main_user_store_money),
                    new MenuBean("充值流程",10001,R.drawable.icon_main_user_store_order),
                    new MenuBean("加入推广计划",10003,R.drawable.icon_main_user_tuiguangjihua)
//                    new MenuBean("我要开播",OPEN,R.drawable.icon_open_live)
            );
            mainUserSectionBean2.setMenuBeanList(list2);
            list.add(mainUserSectionBean2);
            return list;
        }).flatMap(new Function<List<MainUserSectionBean>, ObservableSource<List<MainUserSectionBean>>>() {
            @Override
            public ObservableSource<List<MainUserSectionBean>> apply(List<MainUserSectionBean> list) throws Exception {
                return MainAPI.getMenuUser(list,CONNECT_SERVICE,SETTING);
            }
        }).subscribe(new DefaultObserver<List<MainUserSectionBean>>() {
            @Override
            public void onNext(List<MainUserSectionBean> list) {
                if(mMenuUserAdapter!=null){
                    mMenuUserAdapter.setData(list);
                }
            }
        });
    }
    private JSONObject mUserJsonObject;
    private void parseUserCenterOntherData(JSONObject info) {
        mUserJsonObject=info;
        String userJson=info.toJSONString();
        UserBean userBean= JSON.parseObject(userJson,UserBean.class);
        userBean.setIsVip(info.getIntValue("isVip")==1);
        userBean.setVip(userBean.isVip());
        CommonAppConfig.setUserBean(userBean);
        JSONObject orderStatusJsonObject=info.getJSONObject("orderStatusNum");
        if(orderStatusJsonObject!=null){
            OrderStatementBean userOrderNumBean=orderStatusJsonObject.toJavaObject(OrderStatementBean.class);
            setOrderNumCount(userOrderNumBean);
        }
        setUserMessage();
        String spread_order_count=info.getIntValue("order_count")+"";
        String spread_count=info.getInteger("spread_total")+"";
        String yesterDay=info.getString("yesterDay");
        String brokerage_price=info.getString("brokerage_price");
        if(mTvCurrentMoney!=null){
            mTvCurrentMoney.setText(brokerage_price);
        }
        if(mTvYesterdayMoney!=null){
            mTvYesterdayMoney.setText(yesterDay);
        }
        if(mTvSpreadPersonNum!=null){
            String personString= spread_count+"人";
            int startIndex=personString.indexOf("人");
            SpannableStringBuilder style = new SpannableStringBuilder(personString);
            style.setSpan(new AbsoluteSizeSpan(10, true), startIndex, startIndex+1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            mTvSpreadPersonNum.setText(style);
        }
        if(mTvSpreadNum!=null){
            String numString= spread_order_count+"单";
            int startIndex=numString.indexOf("单");
            SpannableStringBuilder style = new SpannableStringBuilder(numString);
            style.setSpan(new AbsoluteSizeSpan(10, true), startIndex, startIndex+1, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
            mTvSpreadNum.setText(style);
        }
    }
    private void setUserMessage() {
        UserBean userBean=CommonAppConfig.getUserBean();
        if(userBean!=null){
            mImgAvator.setVisibility(View.VISIBLE);
            mTvUserName.setVisibility(View.VISIBLE);
            mTvUserId.setVisibility(View.VISIBLE);
            if (!TextUtils.isEmpty(userBean.getAvatar()) && !userBean.getAvatar().startsWith("http")) {
                String url = CommonAppConfig.HOST + userBean.getAvatar();
                FileUtils.Companion.load(url,mImgAvator,true);
            } else {
                FileUtils.Companion.load(userBean.getAvatar(),mImgAvator,true);
            }
            mTvUserName.setText(userBean.getUserNiceName());
            try {
                int aFloat = (int) Float.parseFloat(userBean.getCoin());
                mTvUserId.setText("钻石: "+ aFloat);
            } catch (NumberFormatException e) {
                mTvUserId.setText("钻石: "+ userBean.getCoin());
            }
        }
    }
    private void setOrderNumCount(OrderStatementBean userOrderNumBean) {
        setTextAndViewsibleByNumber(mPointWaitPay,userOrderNumBean.getUnpaidCount());
        setTextAndViewsibleByNumber(mPointWaitDelivered,userOrderNumBean.getUnShippedCount());
        setTextAndViewsibleByNumber(mPointWaitReceived,userOrderNumBean.getReceivedCount());
        setTextAndViewsibleByNumber(mPointWaitEvaluated,userOrderNumBean.getEvaluatedCount());
        setTextAndViewsibleByNumber(mPointWaitRefund,userOrderNumBean.getRefundCount());
    }
    public static void setTextAndViewsibleByNumber(TextView view,Integer number){
        if(number==null){
            return;
        }
        if(number==0){
            view.setVisibility(View.INVISIBLE);
        }else{
            view.setText(Integer.toString(number));
            view.setVisibility(View.VISIBLE);
        }
    }
    @Override
    public void onClick(@Nullable View v) {
        if(!JumpInterceptor.canClick()){
            return;
        }
        int id=v.getId();
    }

    @Override
    public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if(!JumpInterceptor.canClick()){
            return;
        }
        MenuUserAdapter menuUserAdapter= (MenuUserAdapter) adapter;
        MenuBean menuBean=menuUserAdapter.getItem(position);
        if(menuBean==null){
            DebugUtil.sendException("MenuBean==null");
            return;
        }
        int menuId=menuBean.getId();
        HttpCallback callback = new HttpCallback() {
            @Override
            public void onSuccess(int code, String msg, String[] info) {
                if (code == 200 && info.length > 0) {
                    mImgVip.setVisibility(View.VISIBLE);
                } else {
                    mImgVip.setVisibility(View.GONE);ToastUtil.showToast(msg);
                }
                requestData();
            }
        };
        switch (menuId){
            case 9001: // 日卡
                MainAPI.sendGift("999", "999", 1, "1", callback);
                return;
            case 9002: // 月卡
                MainAPI.sendGift("999", "999", 2, "1", callback);
                return;
            case 9003: // 年卡
                MainAPI.sendGift("999", "999", 3, "1", callback);
                return;
            case 10001: // 充值流程
                WebViewActivity.Companion.start(requireActivity(), "http://web.nowk.top//appapi/page/detail?id=3");
                return;
            case 10002: // 去充值
                MainAPI.getChargeUrl(new HttpCallback() {
                    @Override
                    public void onSuccess(int code, String msg, String[] info) {
                        String data = msg;
                        /*http://192.168.1.4/web/charge.php?uuid=efba26fd-6df2-482a-bb8b-3a4db31e234d&_=1709649224*/
                        Bitmap qrCode = CodeUtils.createQRCode("http://web.nowk.top/web/charge.php?uuid="+data+"&_="+new Date(), 600, null);
                        if (requireActivity() instanceof MainActivity) {
                            ((MainActivity)requireActivity()).toShowChargeUrl(qrCode);
                        }else if (requireActivity() instanceof MyDetailActivity) {
                            ((MyDetailActivity)requireActivity()).toShowChargeUrl(qrCode);
                        }
                    }
                });
                return;
            case 10003: // 加入推广计划
                startActivity(new Intent(requireActivity(), JoinTuiGuangActivity.class));
                return;
//            case MY_MONEY:
//                toMyCoin();
//                break;
//            case MY_ADDR:
//                toMyAddress();
//                break;
//            case MY_COLLECT:
//                toCollectGoods();
//                break;
//            case CONNECT_SERVICE:
//                openService();
//                break;
//            case SETTING:
//                startActivity(SettingActivity.class);
//                break;
//            case CONSIGNMENT_GOOD_MANNGER:
//                break;
//            case STORE_ORDER:
//                StoreOrderListActivity.forward(getActivity(), ShopState.ORDER_SELL_STORE);
//                break;
//            case CONSIGNMENT_ORDER:
//                break;
//            case STORE_MONEY:
//                ProfitActivity.forward(getActivity(),ProfitActivity.TYPE_STORE);
//                break;
//            case CONSIGNMENT_MONEY:
//                ProfitActivity.forward(getActivity(),ProfitActivity.TYPE_CONSIGNMENT);
//                break;
//            case OPENSTORE:
//                startActivity(ApplyStoreActivity.class);
//                break;
//            case MY_DIAMONDS:
//                MyDiamondsActivity.forward(getActivity());
//                break;
//            case GIFT_PROFIT:
//                GiftProfitActivity.forward(getActivity());
//                break;
//
//            case OPEN:
//                ( (MainActivity)getActivity()).openLive(null);
//                break;
//            default:
//                break;
        }
        if (view.getTag() instanceof MenuBean) {
            String url = ((MenuBean) view.getTag()).getUrl();
            if (url.startsWith("http")) {
                WebViewActivity.Companion.start(requireActivity(), url);
                return;
            }
        }
        ToastUtil.showToast("更多功能敬请期待");
    }
}
